package enterprise

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"insighttracking/query/dao"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type ModifyEnterpriseStatusByIdApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewModifyEnterpriseStatusByIdApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *ModifyEnterpriseStatusByIdApiLogic {
	hostname, _ := os.Hostname()
	return &ModifyEnterpriseStatusByIdApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *ModifyEnterpriseStatusByIdApiLogic) ModifyEnterpriseStatusByIdApi(req *types.IdReq) (resp string, err error) {
	// todo: add your logic here and delete this line
	enterpriseEntity, err := service.EnterpriseService.GetByIdApi(l.ctx, req.Id)
	if err != nil {
		return "", errors.New("传递的id错误")
	}
	tx := dao.Use(l.svcCtx.MysqlDb).Begin()
	// 企业状态
	status := k.If(enterpriseEntity.Status == 0, 1, 0)
	if err = service.EnterpriseService.ModifyStatusByIdApi(l.ctx, tx, req.Id, int64(status)); err != nil {
		if err := tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("修改失败")
	}
	if status == 1 {
		// 门店状态
		if err = service.EnterpriseCustomerService.ModifyStatusByEnterpriseIdApi(l.ctx, tx, req.Id, int64(status)); err != nil {
			if err = tx.Rollback(); err != nil {
				return "", err
			}
			return "", errors.New("修改失败")
		}
		if err = service.EnterprisePersonService.ModifyByEnterpriseIdApi(l.ctx, tx, req.Id, int64(status)); err != nil {
			if err = tx.Rollback(); err != nil {
				return "", err
			}
			return "", errors.New("修改失败")
		}
		// 修改账号的
		if err = service.AccountService.ModifyStatusByEnterpriseIdApi(l.ctx, tx, req.Id, int64(status+1)); err != nil {
			if err = tx.Rollback(); err != nil {
				return "", err
			}
			return "", errors.New("修改失败")
		}
	}
	if err = tx.Commit(); err != nil {
		return "", errors.New("修改失败")
	}
	return "修改成功", nil
}
